import React, { useRef, useEffect } from 'react';
import {
  View,
  StyleSheet,
  PanResponder,
  Animated,
  Dimensions,
  StyleProp,
  ViewStyle,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { colors, shadows, size, spacing } from '../styles';

const { height: SCREEN_HEIGHT } = Dimensions.get('screen');

interface DraggablePanelProps {
  /**
   * 面板内容
   */
  children: React.ReactNode;

  /**
   * 面板全屏最大高度，默认为SafeViewHeight
   */
  fullScreenHeight?: number;
  /**
   * 面板完全展开时的高度，默认为屏幕高度的 1/3
   */
  containerHeight?: number;

  /**
   * 面板折叠时的高度，默认为屏幕高度的 1/6
   */
  collapsedHeight?: number;

  /**
   * 面板初始状态是否折叠，默认为 false
   */
  collapsed?: boolean;

  /**
   * 初始化时是否全屏展示
   */
  initialFullScreen?: boolean;

  /**
   * 重叠渐变高度
   */
  overlapHeight?: number;

  /**
   * 面板折叠状态改变时的回调函数
   */
  onCollapseChange?: (collapsed: boolean) => void;
  /**
   * 面板全屏状态改变时的回调函数
   */
  onFullScreenChange?: (fullScreen: boolean) => void;

  /**
   * 自定义面板样式
   */
  style?: StyleProp<ViewStyle>;
}

const DraggablePanel: React.FC<DraggablePanelProps> = ({
  children,
  fullScreenHeight,
  containerHeight = SCREEN_HEIGHT * 0.5,
  collapsedHeight = SCREEN_HEIGHT * 0.2,
  collapsed = true,
  initialFullScreen = false,
  overlapHeight = 0,
  onCollapseChange,
  onFullScreenChange,
  style,
}) => {
  const insets = useSafeAreaInsets();
  const screenHeight = Dimensions.get('screen').height; // 获取整个屏幕的高度
  const safeAreaHeight =
    fullScreenHeight || screenHeight - insets.top - insets.bottom; // 计算安全区域的高度，考虑顶部和底部

  // 使用 refs 存储最新的高度值，确保在 PanResponder 中能获取到最新值
  const containerHeightRef = useRef(containerHeight);
  const collapsedHeightRef = useRef(collapsedHeight);
  const overlapHeightRef = useRef(overlapHeight);

  useEffect(() => {
    containerHeightRef.current = containerHeight;
  }, [containerHeight]);

  useEffect(() => {
    collapsedHeightRef.current = collapsedHeight;
  }, [collapsedHeight]);

  useEffect(() => {
    overlapHeightRef.current = overlapHeight;
  }, [overlapHeight]);

  // 面板高度的动画值
  const panelHeight = useRef(
    new Animated.Value(
      collapsed
        ? collapsedHeight
        : initialFullScreen
        ? safeAreaHeight
        : containerHeight,
    ),
  ).current;

  // 面板是否完全展开到顶部的状态
  const isFullyExpanded = useRef(
    new Animated.Value(
      collapsed
        ? 0
        : initialFullScreen || containerHeight >= safeAreaHeight
        ? 1
        : 0,
    ),
  ).current;

  // 当前面板位置的引用
  const currentPosition = useRef(
    collapsed
      ? collapsedHeight
      : initialFullScreen
      ? safeAreaHeight
      : containerHeight,
  );

  useEffect(() => {
    const targetHeight = collapsed
      ? collapsedHeight
      : initialFullScreen
      ? safeAreaHeight
      : containerHeight;
    Animated.timing(panelHeight, {
      toValue: targetHeight,
      duration: 300,
      useNativeDriver: false,
    }).start();

    // 更新完全展开状态
    Animated.timing(isFullyExpanded, {
      toValue: collapsed
        ? 0
        : initialFullScreen || containerHeight >= safeAreaHeight
        ? 1
        : 0,
      duration: 300,
      useNativeDriver: false,
    }).start();

    currentPosition.current = targetHeight;
  }, [
    collapsed,
    collapsedHeight,
    containerHeight,
    panelHeight,
    isFullyExpanded,
    initialFullScreen,
    safeAreaHeight,
  ]);

  // 创建手势响应系统
  const panResponder = useRef(
    PanResponder.create({
      // 要求成为响应者
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => {
        // 只有当垂直移动距离大于水平移动距离且移动距离足够大时才响应
        return Math.abs(gestureState.dy) > Math.abs(gestureState.dx) && Math.abs(gestureState.dy) > 5;
      },
      onPanResponderGrant: (_, gestureState) => {
        // 当手势开始时，停止动画，让用户可以直接控制面板
        panelHeight.stopAnimation();
      },

      // 用户开始拖拽时的处理
      onPanResponderMove: (_, gestureState) => {
        // 计算新的面板高度，确保在有效范围内
        const newHeight = Math.max(
          collapsedHeightRef.current,
          Math.min(safeAreaHeight, currentPosition.current - gestureState.dy),
        );
        panelHeight.setValue(newHeight);

        // 更新完全展开状态
        isFullyExpanded.setValue(newHeight >= safeAreaHeight ? 1 : 0);
      },

      // 用户结束拖拽时的处理
      onPanResponderRelease: (_, gestureState) => {
        // 更新当前位置引用
        currentPosition.current = currentPosition.current - gestureState.dy;
        
        // 计算释放时的面板高度
        const newHeight = Math.max(
          collapsedHeightRef.current,
          Math.min(safeAreaHeight, currentPosition.current),
        );

        // 确定面板应该停靠的位置
        let snappedHeight = Math.min(
          containerHeightRef.current,
          safeAreaHeight,
        );
        let isCollapsed = false;

        // 根据当前位置决定停靠点
        if (newHeight <= (collapsedHeightRef.current + snappedHeight) / 2) {
          snappedHeight = collapsedHeightRef.current;
          isCollapsed = true;
        } else if (newHeight > (snappedHeight + safeAreaHeight) / 2) {
          snappedHeight = safeAreaHeight;
        }
        // 使用动画过渡到目标高度
        Animated.spring(panelHeight, {
          toValue: snappedHeight,
          useNativeDriver: false,
        }).start();

        // 更新完全展开状态
        Animated.spring(isFullyExpanded, {
          toValue: snappedHeight >= safeAreaHeight ? 1 : 0,
          useNativeDriver: false,
        }).start();

        // 更新当前位置引用
        currentPosition.current = snappedHeight;

        onFullScreenChange?.(snappedHeight >= safeAreaHeight);

        // 触发折叠状态改变回调
        onCollapseChange?.(isCollapsed);
      },
    }),
  ).current;

  return (
    <Animated.View
      {...panResponder.panHandlers}
      style={[
        styles.panelContainer,
        !isFullyExpanded && styles.halfPanelContainer,
        {
          height: panelHeight,
          borderTopLeftRadius: isFullyExpanded.interpolate({
            inputRange: [0, 1],
            outputRange: [spacing.radii.md, 0],
          }),
          borderTopRightRadius: isFullyExpanded.interpolate({
            inputRange: [0, 1],
            outputRange: [spacing.radii.md, 0],
          }),
        },
        style,
      ]}
    >
      {/* 拖拽手柄区域 - 当面板完全展开到顶部时隐藏 */}
      <Animated.View
        style={[
          styles.dragHandleContainer,
          {
            opacity: isFullyExpanded.interpolate({
              inputRange: [0, 1],
              outputRange: [1, 0],
            }),
          },
        ]}
      >
        <View style={styles.dragHandle} />
      </Animated.View>

      {/* 面板内容区域 */}
      <View style={styles.contentContainer}>{children}</View>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  panelContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: colors.background,
    zIndex: 1,
  },
  halfPanelContainer: {
    ...shadows.lg,
  },
  dragHandleContainer: {
    alignItems: 'center',
    paddingVertical: spacing.padding.sm,
    backgroundColor: 'transparent',
  },
  dragHandle: {
    width: size(10),
    height: size(1),
    borderRadius: spacing.radii.sm,
    backgroundColor: colors.gray,
  },
  contentContainer: {
    flex: 1,
  },
});

export default DraggablePanel;